package com.wtz.util.learn.stringutils;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

import java.util.Objects;

/**
 * Date: 2020/10/10
 * Company: www.dtstack.com
 *
 * @author tiezhu
 */
public class CommandLineDemo {
    public static void main(String[] args) throws ParseException {
        Options options = new Options();
        Option optionOne = new Option("t", "topic", true, "topic name");
        optionOne.setRequired(true);
        Option optionTwo = new Option("h", "help", false, "disable pagination of output");
        optionTwo.setRequired(false);

        options.addOption(optionOne);
        options.addOption(optionTwo);

        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.setWidth(100);

        CommandLineParser parser = new DefaultParser();
        CommandLine commandLine = parser.parse(options, args);

        if (commandLine.hasOption('h')) {
            helpFormatter.printHelp("this is a help info", options);
        }

        System.out.println("-------------------------------");
        Option[] lineOptions = commandLine.getOptions();
        if (Objects.nonNull(lineOptions)) {
            for (Option lineOption : lineOptions) {
                String name = lineOption.getLongOpt();
                String value = commandLine.getOptionValue(name);
                System.out.println(name + " >> " + value);
            }
        }
    }
}
